var express = require('express');
var router = express.Router();

const log4js = require('log4js');//日志模块

log4js.configure({
  appenders: {
    console: { type: 'console' },
    file: { type: 'file', filename: 'error.log' }
  },
  categories: {
    default: { appenders: ['console'], level: 'debug' },
    log4jslog: { appenders: ['file'], level: 'debug' }
  }
});

const logger = log4js.getLogger('log4jslog');

/* GET home page. */
router.post('/', function (req, res, next) {
    // var seed = req.query.seed;
    // // var cookie = "2cff472d9fffc552990167186eb72a764479c287";
    // var funIndex = strToLong(seed) % arrFun.length;
    // var fun = arrFun[funIndex];
    // //res.send(fun(seed));
    //
    // res.status(200).send(fun(seed))
    var cookie;
    var result;
    if (req.body.code) {
        code = req.body.code;
        host = req.body.host;

        //console.log(code);
        eval(code);

        // 初步判断变量是否正确，存在var碰巧正确的情况
        varArray = result.substring(0, 3);
        if (varArray != "var") {
            res.send({"status": "fail"});
            return;
        }
        // 再判断document变量位置是否正确
        docArray = result.match(/document.cookie=(\S+)+/);
        if (docArray == null) {
            res.send({"status": "fail"});
            return;
        }
        setArray = result.match(/setTimeout\((\S+),1500\)/);
        if (setArray == null) {
            res.send({"status": "fail"});
            return;
        }

        // 进行正则捕获，不同加密代码内容不同，可能不含正则字段
        funcArray = result.match(/'onreadystatechange',(\S+)\)}/);
        if (funcArray != null) {
            funcName = funcArray[1];
        }
        else{
            res.send({"status": "fail"});
            return;
        }

        divArray = result.match(/for\(var (\S+)=0;/);
        if (divArray != null) {
            divName = divArray[1];
        }
        else{
            divArray == ""
            //res.send({"status": "div array fail"});
            //return;
        }

        matchArray = result.match(/var (\S+)=\[function\(/);
        if (matchArray != null) {
            matchName = matchArray[1];
        }
        else{
            matchArray == ""
            //res.send({"status": "match array fail"});
            //return;
        }

        // 替换 while(window._phantom||window.__phantomas){};
        result = result.replace("while(window._phantom||window.__phantomas){};", "");

        // 替换 setTimeout('location.href=location.pathname+location.search.replace(/[\\?|&]captcha-challenge/,\\'\\')', 1500);
        result = result.replace("setTimeout('location.href=location.pathname+location.search.replace(/[\\?|&]captcha-challenge/,\\'\\')',1500);", "");

        // 替换 setTimeout('location.href=location.href.replace(/[\\?|&]captcha-challenge/,\\'\\')',1500);
        result = result.replace("setTimeout('location.href=location.href.replace(/[\\?|&]captcha-challenge/,\\'\\')',1500);", "");

        // 替换 if((function(){try{return !!window.addEventListener;}catch(e){return false;}})()){document.addEventListener('DOMContentLoaded',l,false);}else{document.attachEvent('onreadystatechange',l);}
        result = result.replace("if((function(){try{return !!window.addEventListener;}catch(e){return false;}})()){document.addEventListener('DOMContentLoaded',"+funcName+",false)}else{document.attachEvent('onreadystatechange',"+funcName+")}", "");

        // 替换 document.cookie=
        result = result.replace("document.cookie=", "return");

        hostArray = result.match(/(\S+)=document.createElement\('div'\);/);
        if (hostArray != null) {
            // 替换h变量 h=document.createElement('div');h.innerHTML='<a href=\'/\'>x</a>';h=h.firstChild.href;var r=h.match(/https?:\/\//)[0];h=h.substr(r.length).toLowerCase();
            var new_str = funcName +  "='" + host + "';";
            result = result.replace(funcName + "=document.createElement('div');"+funcName+".innerHTML='<a href=\\'/\\'>"+divName+"</a>';"+funcName+"="+funcName+".firstChild.href;var "+matchName+"="+funcName+".match(/https?:\\/\\//)[0];"+funcName+"="+funcName+".substr("+matchName+".length).toLowerCase();", new_str);
        }
        //console.log(result)

        // 定义cookie方法
        try{
            eval(result);
        }catch(err){
            logger.warn("define_error:" + result);
        }
        // console.log("funcName: %s", funcName);

        try{
            // nodejs环境与浏览器不同没有全局变量window，需要伪装一个
            var window = "window"
            // 执行cookie方法
            cookie = eval(funcName + "();");

            //console.log("cookie = %s", cookie);

            res.send({"status": "success", "result": cookie});
        }catch(err){
            logger.warn("execute_error:" + funcName);
        }
    }

    else {
        res.send({"status": "fail"});
    }
});

module.exports = router;
